package com.example.myapplication.ui.fragment.collect

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.activity.collect.MyCollectionViewModel
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.example.myapplication.ui.vm.SharedViewModel
import com.kun.base.env.Env
import com.kun.base.ui.AbsBaseFragment
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*

/**
 *文章收藏的页面
 *
 * @author : Kun
 * @date : 2021/6/7
 * @time : 17:25
 */
class ArticleCollectFragment : AbsBaseFragment() {
    private var index = 0
    private lateinit var articleAdapter: ArticleAdapter

    private lateinit var articleCollectViewModel: ArticleCollectViewModel
    private lateinit var sharedViewModel: SharedViewModel
    private lateinit var myCollectionViewModel: MyCollectionViewModel
    override fun getLayoutId(): Int {
        return R.layout.fragment_article_collect
    }

    override fun initViewModel() {
        articleCollectViewModel = getFragmentScopeViewModel(ArticleCollectViewModel::class.java)
        sharedViewModel=getApplicationScopeViewModel(SharedViewModel::class.java)
        myCollectionViewModel=getActivityScopeViewModel(MyCollectionViewModel::class.java)
        myCollectionViewModel.unCollectArticle.observe(this , Observer { t->
            if(t==0){
                index = 0
                getData()
            }
        })
        sharedViewModel.unCollectArticle.observe(this, Observer {
            refresh_layout!!.autoRefresh()
        })
        initCollectArticleResult()
        initDelCollectArticle()
    }

    override fun initView() {
        refresh_layout!!.setRefreshHeader(ClassicsHeader(activity))

        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.type = 1
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        recycler_view!!.layoutManager = LinearLayoutManager(activity)
        recycler_view!!.adapter = articleAdapter

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 0
            getData()
        }

        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true
        }

        getData()
    }

    /**
     * 加载文章列表
     */
    private fun getData() {
        articleCollectViewModel.requestCollectArticle(index)
    }

    /**
     *收藏文章列表接口返回结果
     */
    private fun initCollectArticleResult() {
        articleCollectViewModel.collectRequest.collectArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                if (t.data!!.curPage == 1) {
                    articleAdapter.setList(t.data!!.datas)
                } else {
                    articleAdapter.addData(t.data!!.datas)
                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    articleAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    articleAdapter.loadMoreModule.loadMoreComplete()
                }
            } else {
                articleAdapter.loadMoreModule.loadMoreComplete()
            }
            refresh_layout!!.finishRefresh()

        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        articleCollectViewModel.collectRequest.delArticleResultForMe.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            sharedViewModel.unCollectArticle.value=i.originId
                            list.remove(i)
                            break
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(activity!!).apply {
            addSelectItems("打开链接", "删除")
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else {
                        articleCollectViewModel.requestDelCollectArticleForMe(
                            articleBean.id,
                            articleBean.originId
                        )
                    }
                    dismiss()
                }
            })
        }.show()
    }
}